package com.xinxin.facelinker.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chatuidemo.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xinxin.facelinker.Config;
import com.xinxin.facelinker.adapter.ShowMyMotionAdapter;
import com.xinxin.facelinker.domain.ShowMyMotion;
import com.xinxin.facelinker.ui.button.views.ButtonFloat;
import com.xinxin.facelinker.ui.menu.ContextMenuDialogFragment;
import com.xinxin.facelinker.ui.menu.MenuObject;
import com.xinxin.facelinker.ui.menu.MenuParams;
import com.xinxin.facelinker.ui.menu.interfaces.OnMenuItemClickListener;
import com.xinxin.facelinker.ui.menu.interfaces.OnMenuItemLongClickListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ShowMyMotionActivity extends FragmentActivity implements OnMenuItemClickListener,
        OnMenuItemLongClickListener {
    private ListView lvMyMotion;
    private ButtonFloat btnMenu;
    private String my_account_num;
    private List<ShowMyMotion> list = new ArrayList<ShowMyMotion>();
    private HttpUtils httpUtils = new HttpUtils();
    private View btnBack;
    private FragmentManager fragmentManager = getSupportFragmentManager();
    private DialogFragment mMenuDialogFragment;
    private ShowMyMotionAdapter adapter;
    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/background.jpg";
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);
    private static final String PHOTO_FILE_LOCATION = "file:///sdcard/photo.jpg";
    Uri photoUrl = Uri.parse(PHOTO_FILE_LOCATION);
    private ImageView ivMyMotionBackground;
    private ImageView ivMyMotionPhoto;
    private TextView tvNickname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_my_motion);

        lvMyMotion = (ListView) findViewById(R.id.lvMyMotion);
        btnMenu = (ButtonFloat) findViewById(R.id.btnMenu);
        btnBack = findViewById(R.id.btnBack);
        my_account_num = getIntent().getStringExtra(Config.KEY_MY_ACCOUNT_NUM);
        lvMyMotion.setAdapter(adapter);

        getMyMotion();

        initMenuFragment();

        btnMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMenuDialogFragment.onAttach(ShowMyMotionActivity.this);
                fragmentManager.beginTransaction().add(mMenuDialogFragment, "").commit();
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getMyMotion(){
        final RequestParams params = new RequestParams();
        params.addBodyParameter(Config.ACTION, Config.ACTION_SHOW_MY_MOTION);
        params.addBodyParameter(Config.KEY_MY_ACCOUNT_NUM, my_account_num);
        httpUtils.send(HttpRequest.HttpMethod.POST, Config.CATEGORIES_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                list = gson.fromJson(responseInfo.result, new TypeToken<ArrayList<ShowMyMotion>>() {
                }.getType());
                adapter = new ShowMyMotionAdapter(ShowMyMotionActivity.this, list);
                lvMyMotion.setAdapter(adapter);
                getHearder(list);

                lvMyMotion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        Intent intent = new Intent(ShowMyMotionActivity.this, ShowMotionActivity.class);
                        intent.putExtra(Config.KEY_MOTION_PHOTO_URL, list.get(position).getMotion_photo_url());
                        intent.putExtra(Config.KEY_MOTION_ID, list.get(position).getMotion_id());
                        intent.putExtra(Config.KEY_MOTION, list.get(position).getMotion());
                        intent.putExtra(Config.KEY_PHOTO_URL, list.get(position).getPhoto_url());
                        intent.putExtra(Config.KEY_DATE, list.get(position).getDate());
                        intent.putExtra(Config.KEY_NICKNAME, list.get(position).getNickname());
                        startActivity(intent);
                    }
                });

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(ShowMyMotionActivity.this, R.string.show_my_motion_fail, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getHearder(List<ShowMyMotion> list){

        ImageLoader imageLoader=ImageLoader.getInstance();
        LayoutInflater layoutInflater=getLayoutInflater();
        View header = layoutInflater.inflate(R.layout.layout_show_my_motion_header, null);

        ivMyMotionBackground = (ImageView) header.findViewById(R.id.ivMyMotionBackground);
        ivMyMotionPhoto = (ImageView) header.findViewById(R.id.ivMyMotionPhoto);
        tvNickname= (TextView) header.findViewById(R.id.tvNickname);


//        ivMyMotionBackground.setScaleType(ImageView.ScaleType.CENTER_CROP);
//        ivMyMotionPhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
//
//        imageLoader.displayImage(list.get(0).getPhoto_url(), ivMyMotionBackground);
//        imageLoader.displayImage(list.get(0).getPhoto_url(), ivMyMotionPhoto);
//        tvNickname.setText(list.get(0).getNickname());
//
//        ivMyMotionPhoto.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.setType("image/*");
//                startActivityForResult(intent, 3);
//            }
//        });
//
//        ivMyMotionBackground.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
//                intent.setType("image/*");
//                startActivityForResult(intent, 1);
//            }
//        });

        lvMyMotion.addHeaderView(header);
    }

    private void initMenuFragment() {
        MenuParams menuParams = new MenuParams();
        menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
        menuParams.setMenuObjects(getMenuObjects());
        menuParams.setClosableOutside(false);
        mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
    }

    private List<MenuObject> getMenuObjects() {

        List<MenuObject> menuObjects = new ArrayList<>();

        MenuObject close = new MenuObject();
        close.setResource(R.drawable.btn_close);

        MenuObject pals_motion = new MenuObject("朋友圈");
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.btn_pals_motion);
        pals_motion.setBitmap(b);

        MenuObject male_toplist = new MenuObject("男神榜");
        b = BitmapFactory.decodeResource(getResources(), R.drawable.btn_male_toplist);
        male_toplist.setBitmap(b);

        MenuObject near_pal = new MenuObject("附近的人");
        BitmapDrawable bd = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), R.drawable.btn_near_pal));
        near_pal.setDrawable(bd);

        MenuObject blacklist = new MenuObject("黑名单");
        b = BitmapFactory.decodeResource(getResources(), R.drawable.btn_blacklist);
        blacklist.setBitmap(b);

        MenuObject female_toplist = new MenuObject("女神榜");
        b = BitmapFactory.decodeResource(getResources(), R.drawable.btn_female_toplist);
        female_toplist.setBitmap(b);

        MenuObject add_motion = new MenuObject("添加动态");
        b = BitmapFactory.decodeResource(getResources(), R.drawable.btn_add);
        add_motion.setBitmap(b);

        menuObjects.add(close);
        menuObjects.add(pals_motion);
        menuObjects.add(near_pal);
        menuObjects.add(female_toplist);
        menuObjects.add(male_toplist);
        menuObjects.add(blacklist);
        menuObjects.add(add_motion);

        return menuObjects;
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_image:
                if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
                    mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
            mMenuDialogFragment.dismiss();
        } else {
            finish();
        }
    }

    public void onMenuItemClick(View clickedView, int position) {
        if (position == 1) {
            Intent intent = new Intent(ShowMyMotionActivity.this, MainActivity.class);
            startActivity(intent);
            finish();

        } else if (position == 2) {
            Intent intent = new Intent(ShowMyMotionActivity.this, ShowNearUserMotionActivity.class);
            startActivity(intent);
            finish();

        } else if (position == 3) {
            Intent intent = new Intent(ShowMyMotionActivity.this, ShowFemaleToplistActivity.class);
            startActivity(intent);
            finish();

        } else if (position == 4) {
            Intent intent = new Intent(ShowMyMotionActivity.this, ShowMaleToplistActivity.class);
            startActivity(intent);
            finish();

        } else if (position == 5) {
            Intent intent = new Intent(ShowMyMotionActivity.this, ShowBlacklistActivity.class);
            startActivity(intent);
            finish();
        }else if(position==6){
            Intent intent = new Intent(ShowMyMotionActivity.this, AddMyMotionActivity.class);
            startActivity(intent);
        }
    }

    public void onMenuItemLongClick(View clickedView, int position) {
    }

    //转变uri为file类型
    private Uri convertUri(Uri uri){
        InputStream is=null;
        try {
            is=getContentResolver().openInputStream(uri);
            Bitmap bitmap= BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //将Bitmap转变为file类型Uri
    private Uri saveBitmap(Bitmap bitmap){
        File tmpDir=new File(Environment.getExternalStorageDirectory()+"/com.xinxin.faceliner");
        if(!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        File img=new File(tmpDir.getAbsolutePath()+"userpicture.png");
        try {
            FileOutputStream fos=new FileOutputStream(img);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //对图像进行裁剪
    private void startImageZoom(Uri uri){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, 2);
    }

    private void startImageZoom2(Uri uri){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUrl);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent,4);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==1){

            if(data==null)
                return;
            else {
                Uri uri;
                uri = data.getData();
                Uri fileUri = convertUri(uri);

                //向数据库中保存图片地址
                startImageZoom(fileUri);
            }

        }else if(requestCode==2){

            if(imageUri != null){
                Bitmap bitmap = decodeUriAsBitmap(imageUri);
                ivMyMotionBackground.setImageBitmap(bitmap);
                photoChange(Config.KEY_PICTURE_URL,imageUri.toString());
            }
        }else if(requestCode==3){
            if(data==null)
                return;
            else {
                Uri uri;
                uri = data.getData();
                Uri fileUri = convertUri(uri);

                //向数据库中保存图片地址
                startImageZoom2(fileUri);
            }
        }else if(requestCode==4){
            if(photoUrl != null){
                Bitmap bitmap = decodeUriAsBitmap(photoUrl);
                ivMyMotionPhoto.setImageBitmap(bitmap);
                photoChange(Config.KEY_PHOTO_URL,photoUrl.toString());
            }
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    private void photoChange(String key,String url){
        RequestParams params = new RequestParams();
        params.addBodyParameter(Config.ACTION, Config.ACTION_PHOTO_CHANGE);
        params.addBodyParameter(Config.KEY_MY_ACCOUNT_NUM, my_account_num);
        params.addBodyParameter(key, url);

        httpUtils.send(HttpRequest.HttpMethod.POST, Config.CATEGORIES_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }
}
